package org.spdata.tsdb.server;


import java.nio.charset.Charset;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class Server {
	private static Logger logger = LoggerFactory.getLogger(Server.class);
	private boolean closed = false;
	private int port;
	private EventLoopGroup bossGroup = null;
	EventLoopGroup workerGroup = null;
	
	public Server(){
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
	public boolean isClosed() {
		return closed;
	}

	@PreDestroy
	public void destory(){
		this.shutDown();
	}
	
	
	public void shutDown(){
		try {
			 workerGroup.shutdownGracefully();
	         bossGroup.shutdownGracefully();
	         this.closed = true;
	         logger.info("shutdown netty server!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@PostConstruct
	public void start(){
		Timer timer = new Timer();
		timer.schedule(new TimerTask(){
			@Override
			public void run() {
				startServer();
			}
		}, 1000);
	}
	
	
	public void startServer(){
		bossGroup = new NioEventLoopGroup();

        workerGroup = new NioEventLoopGroup();
        try {
        	logger.info("to init server...");
            ServerBootstrap b = new ServerBootstrap(); 
            b.group(bossGroup, workerGroup)
             	.channel(NioServerSocketChannel.class) 
             	.childHandler(new ChannelInitializer<SocketChannel>() { 
	                 @Override
	                 public void initChannel(SocketChannel ch) throws Exception {
	                	 logger.info("init server channel!");
	                	 ch.pipeline().addLast(new LineBasedFrameDecoder(10*1024*1024));
	                	 ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
	                     ch.pipeline().addLast(new ServerHandler());
	                 }
	             })
             	.option(ChannelOption.SO_BACKLOG, 512)          
             	.childOption(ChannelOption.SO_KEEPALIVE, true); 
            ChannelFuture f = b.bind(port).sync();
            logger.info("start server finished! linstener on port {}", port);
            f.channel().closeFuture().sync();
        }catch(Exception e){
        	e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
	}
}
